#-*- coding:utf-8 -*-

from tornado.escape import json_encode
from tornado.web import HTTPError,authenticated
from tornado.escape import json_encode, json_decode
from libs.handler import BaseHandler

import time

from sae.taskqueue import Task, TaskQueue
from libs.category import Category

from libs.sae_fts import SaeFts

import math
'''
 item html page
'''
class Item(BaseHandler):
	def get(self, id):
		ret = self.db.get("SELECT id,title,price,pic_url,volume,nick,click_url,cid,num_iid,like_count,reply_count FROM items WHERE id=%s", id)
		if not ret:
			raise HTTPError(404)
        
		ret["price"] = ret["price"].split(".")
			
		data = self.db.query("SELECT id,title,price,pic_height,num_iid,like_count,reply_count FROM items WHERE cid=%s LIMIT 9",ret["cid"])
		self.render("item.html", item = ret, items = data)

class Hot(BaseHandler):	
	def get(self):
		category = self.get_argument("category","all")
		page = self.get_argument("page","1")
		page = max(1,int(page))

		start_page = self.get_argument("start_page","2")
		cat_info = Category().getId(category)
		start = (page-1)*112+(int(start_page)-1)*16
        
		order = self.get_argument("order", "hot")
		price = self.get_argument("price", "0")
		
		page_size = 16
		
		order_by = "ORDER BY volume DESC"
		if order == "new":
			order_by = "ORDER BY id DESC"
			
		price_type = "1=1"
		if price == "1":
			price_type = "price<100"
		elif price == "2":
			price_type = "price BETWEEN 100 AND 200"
		elif price == "3":
			price_type = "price BETWEEN 200 AND 500"
		elif price == "4":
			price_type = "price>500"
		
		data = self.db.query("SELECT id,title,price,pic_height,num_iid,like_count,reply_count FROM items WHERE group_id=%s AND "+ price_type +" "+order_by+" LIMIT %s,%s",cat_info["group_id"],start,page_size) 

		ret = {}
		ret["page"] = page
		ret['stat'] = 'ok'
		ret['pages'] = 22
		ret["data"] = []
		for val in data:
			val['price'] = str(val['price'])
			html = self.render_string("module/item.html", item = val)
			ret["data"].append(html)
              
		self.write(json_encode(ret))

class New(BaseHandler):
    def post(self):
        from libs.taobao import Taobao
        from libs.utils import get_taobao_id
        
        url = self.get_argument("url",None)
        taobao_id = get_taobao_id(url)

        item = Taobao("item.get").fetch(num_iid = taobao_id,fields = 'num_iid,title,price,pic_url,cid,nick')
	
	if item.has_key("error_response"):
	    self.write(json_encode(item))
	    return 
	else:
	    item = item["item_get_response"]["item"]
	
        try:
	    item["stat"] = 'ok'
	    
            self.db.execute("INSERT INTO items(num_iid,cid,title,price,pic_url,nick,created_at)\
                VALUES(%s,%s,%s,%s,%s,%s,%s)",item["num_iid"],item["cid"], item["title"], item["price"], item["pic_url"], item["nick"], time.time());
	    
	    # 添加到任务
	    queue = TaskQueue('taobao')
	    queue.add(Task("/tools/taobao/complete/"+str(item["num_iid"])))

        except Exception,e:
	    if e[0] == 1062:
		item["stat"] = 'ok'

        self.write(json_encode(item))

class Cat(BaseHandler):
    def get(self, cat):
		cat_info = Category().getId(cat)
		page = self.get_argument("page", "1")
		order = self.get_argument("order", "hot")
		price = self.get_argument("price", "0")
		
		if None == cat_info:
			raise HTTPError(404)
        
		start = (int(page)-1)*112
		
		order_by = "volume"
		if order == "new":
			order_by = "id"
			
		price_type = "1=1"
		if price == "1":
			price_type = "price<100"
		elif price == "2":
			price_type = "price BETWEEN 100 AND 200"
		elif price == "3":
			price_type = "price BETWEEN 200 AND 500"
		elif price == "4":
			price_type = "price>500"
		
		data = self.db.query("SELECT id,title,price,pic_height,\
                num_iid,like_count,reply_count from items WHERE group_id = %s AND "+ price_type +" ORDER BY "+ order_by +" DESC LIMIT %s,16", cat_info["group_id"], start)
		self.render("category.html", item = data, cat = cat, page=page,cat_info = cat_info, tag = Category().get(cat), order_by = order_by,price = price)

class Tag(BaseHandler):
    def get(self,cat, tag):
		
		tag = tag.encode("utf-8")
		in_ajax = self.get_argument("in_ajax", "0")
		page = int(self.get_argument("start_page", 0))
		cat_info = Category().getId(cat)
		search_data = SaeFts().search(tag, "file_long1", "asced", 12, page, option = {"groupid":cat_info["group_id"]})
		
		
		data = self.db.query("SELECT id,title,price,pic_height,\
                num_iid,like_count,reply_count from items WHERE id IN %s", search_data["data"])
		
		if in_ajax == "1":
			ret = {}
			ret["page"] = page
			ret['stat'] = 'ok'
			ret['pages'] = int(math.ceil(search_data["count"]/12))
			ret["data"] = []
			for val in data:
				val['price'] = str(val['price'])
				html = self.render_string("module/item.html", item = val)
				ret["data"].append(html)
			self.write(json_encode(ret))
			return True
		self.render("tag.html", items = data, tag = tag,cat_info = cat_info, tags = Category().get(cat), page=page)

'''
like
'''
class Like(BaseHandler):
	@authenticated
	def post(self):
		id = self.get_argument("id", None)
		
		count = self.db.execute_rowcount("SELECT id FROM likes WHERE user_id=%s AND item_id=%s", self.current_user["id"], id)
		if count == 1:
			self.write(json_encode({"retCode":1}))
			return True;
		self.db.execute("INSERT INTO likes(user_id,item_id,created_at)VALUES(%s,%s,%s)",self.current_user["id"], id, time.time())
		self.db.execute("UPDATE items SET like_count=like_count+1 WHERE id=%s",id)
		self.write(json_encode({"retCode":200}))
		return True;
class UnLike(BaseHandler):
	@authenticated
	def post(self):
		count = self.db.execute_rowcount("DELETE FROM likes WHERE user_id=%s AND item_id=%s", self.current_user["id"], id)
		
handlers = []
handlers = [
        (r"/new",New),
        (r"/(clothes|shoes|bags|accessories|home)/",Cat),
        (r"/ajax/shares.json",Hot),
        (r"/(clothes|shoes|bags|accessories|home)/(.*)",Tag),
		(r"/item/like",Like),
        (r"/item/(\d+).html",Item),
        (r"/(home|bags)/(.*)",Tag)
        ]
